<template>
	<div>
		<van-form @submit="onSubmit">
			<van-field v-model="tel" name="tel" label="电话" placeholder="电话"
				:rules="[{ required: true, message: '请填写用户名' }]" />
			<van-field v-model="code" name="code" center clearable label="短信验证码" placeholder="请输入短信验证码">
				<template #button>
					<van-button :disabled="count !== downTime" @click="curtDownTime" size="small" type="primary"
						native-type="button">
						{{ count === downTime? '发送验证码': '还剩' + count + '秒' }}
					</van-button>
				</template>
			</van-field>
			<div style="margin: 16px;">
				<van-button round block type="info" native-type="submit">提交</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
import axios from 'axios'
import { Notify } from 'vant'
export default {
	data() {
		return {
			tel: '',
			code: '',
			count: 60,
			downTime: 60
		}
	},
	methods: {
		async onSubmit(values) {
			try {
				const resp = await axios.post('/api/tel/login', values);
				Notify({ type: 'success', message: '登录成功' })
				localStorage.setItem('token', resp.data.data)
				this.$router.push('/my')
			} catch {
				Notify({ type: 'danger', message: '手机号或者验证码不正确' })
			}
		}, 
		curtDownTime() {
			axios.get('/api/tel/code').then(resp => {
				console.log(resp.data.data)
				Notify({ type: 'success', message: resp.data.data })
			})

			const timer = setInterval(() => {
				this.count--

				if (this.count <= 0) {
					clearInterval(timer)
					this.count = this.downTime
				}
			}, 1000)
		}
	}
}
</script>